<?php

function mysql_date_to_unixtime( $mysql_date )
{
    if ( preg_match_all( '/(\d{4}?)-(\d{2}?)-(\d{2}?) (\d{2}?):(\d{2}?):(\d{2}?)/', $mysql_date, $mysql_date_regex_result ) )
    {
        $unixtime = mktime(
                            $mysql_date_regex_result[4][0],
                            $mysql_date_regex_result[5][0],
                            $mysql_date_regex_result[6][0],
                            $mysql_date_regex_result[2][0],
                            $mysql_date_regex_result[3][0],
                            $mysql_date_regex_result[1][0]
                            );
        return $unixtime;
    }
    else
    {
        return false;
    }

}

function my_DBG($msg, $mode = 0)
{
    if (is_array($msg))
    {
    	$msg = var_export($msg, TRUE);
    }
    if ($mode == 1)
    {
        $debug = fopen("/tmp/deb.debug", "a");
        @fputs($debug, $_SERVER['SCRIPT_FILENAME']."[DBG ". date("H:i:s d/m") ."]". $msg ."\n");
        fclose($debug);
    }
    else
    {
        echo $_SERVER['SCRIPT_FILENAME']."[DBG ". date("H:i:s d/m") ."]". $msg ." <br/>\n";
    }
}

function is_md5($string)
{
	preg_match('/[a-fA-F0-9]{32}/', $string, $matches);
	if (count($matches) > 0)
	{
		return TRUE;
	}
	return FALSE;
}

function shorten_url_bit_ly($url)
{
	$c = curl_init('http://api.bit.ly/shorten?version=2.0.1&longUrl='.urlencode($url).'&login=hydrarulz&apiKey=R_535d45c3cb122ca23c63ef7dde39427d');
	curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
	$ret = curl_exec($c);
	$aux = json_decode($ret, TRUE);
	$short_url = $aux['results'][$url]['shortUrl'];
	return $short_url;
}

function validate_url($url)
{
	$pattern = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&amp;?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/';
	return preg_match($pattern, $url);
}

function fahrenheit_to_celsius( $Fahrenheit, $decimals = 1 )
{
	$celsius = 5/9 * ( $Fahrenheit - 32 );
	return sprintf( "%.". $decimals ."f", $celsius );
}

function celsius_to_fahrenheit( $Celsius, $decimals = 1 )
{
	$fahrenheit = 9/5 * $Celsius + 32;
	return sprintf( "%.". $decimals ."f", $fahrenheit );
}

function rewrite_string_to_url( $string )
{
	$string_new = preg_replace( '/[^0-9a-zA-Z]/', '_', $string );
	return $string_new;
}

function filter_cross($filterMe)
{
   $tempMe = $filterMe;
   $filterMe = str_replace("&", "&amp;", $filterMe);
   $filterMe = str_replace("<", "&lt;", $filterMe);
   $filterMe = str_replace(">", "&gt;", $filterMe);
   $filterMe = str_replace('"', "&quot;", $filterMe);
   $filterMe = str_replace("'", "&#39;", $filterMe);

   if (strcmp($tempMe,$filterMe))
   {
       //logHacker();
   }
   return $filterMe;
}

function break_url( $Url = NULL )
{
    if ( $Url == NULL )
    {
        $Url = !empty( $_SERVER['SCRIPT_URL'] ) ? $_SERVER['SCRIPT_URL'] : $_SERVER['REQUEST_URI'] ;
    }
    $parts = explode( '/', $Url );
    if ( empty( $parts[0] ) )
    {
        unset( $parts[0] );
        $parts = array_values( $parts );
    }
    return $parts;
}

function get_smarty()
{
    global $_base_path, $_base_url, $_debug;
    $smarty_obj = new Smarty();
    $smarty_obj->template_dir = $_base_path .'/templates';
    $smarty_obj->compile_dir = $_base_path .'/templates_c';
    $smarty_obj->cache_dir = $_base_path .'/templates_cache';
    $smarty_obj->assign( 'base_url', $_base_url );
    if ( $_debug )
    {
        $smarty_obj->force_compile = true;
        $smarty_obj->caching = 0;
    }
    return $smarty_obj;
}

function error_handler( $error_code, $error_message, $error_file, $error_line, $error_context )
{
    global $_path_to_logs;

    $error_type = array (
                E_ERROR              => 'Error',
                E_WARNING            => 'Warning',
                E_PARSE              => 'Parsing Error',
                E_NOTICE             => 'Notice',
                E_CORE_ERROR         => 'Core Error',
                E_CORE_WARNING       => 'Core Warning',
                E_COMPILE_ERROR      => 'Compile Error',
                E_COMPILE_WARNING    => 'Compile Warning',
                E_USER_ERROR         => 'User Error',
                E_USER_WARNING       => 'User Warning',
                E_USER_NOTICE        => 'User Notice',
                E_STRICT             => 'Runtime Notice',
                E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'
                );

	$error_file_name = $_path_to_logs . '_-application-error-log.txt';
	$error_date_time = date("Y-m-d H:i:s (T)");

	$error_content = "<errorentry> \r\n";
	$error_content .= "\t<datetime>{$error_date_time}</datetime> \r\n";
	$error_content .= "\t<error_code>" . $error_type[$error_code] . "</error_code> \r\n";
	$error_content .= "\t<error_message>{$error_message}</error_message> \r\n";
	$error_content .= "\t<error_file>{$error_file}</error_file> \r\n";
	$error_content .= "\t<error_line>{$error_line}</error_line> \r\n";
	$error_content .= "\t<vartrace>: " . print_r( $error_context, true )  . "</vartrace> \r\n";
	$error_content .= "</errorentry> \r\n";

	@$error_file_handler = fopen( $error_file_name, 'a' );
	@fwrite( $error_file_handler, $error_content );
	@fclose( $error_file_handler );

	switch( $error_code )
	{
		case E_USER_ERROR:
			header('Location: application_error.html');
			die();
			return false;
		break;
		default:
			// continua executia
			return true;
		break;
	}
}

// Generate a random character string
function rand_str($length = 32, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
{
    $chars_length = (strlen($chars) - 1);
    $string = $chars{rand(0, $chars_length)};
    for ( $i = 1; $i < $length; $i++ )
    {
        $r = $chars{rand(0, $chars_length)};
        if ($r != $string{$i - 1})
        {
			$string .=  $r;
		}
		else
		{
			$i--;
		}
    }
    return $string;
}

function valid_email($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}


?>
